package com.chagee.store.operation.server.service;

import cn.hutool.core.map.MapUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.chagee.lark.anno.ExceptionLarkNotice;
import com.chagee.lark.enums.UrgentTypeEnum;
import com.chagee.store.operation.api.enums.OrderAppealTypeEnum;
import com.chagee.store.operation.api.response.SearchSupplierResponse;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.config.SupplierConfirmationConfig;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.StoreMapper;
import com.chagee.store.operation.server.event.dao.StoreTaskRelationMapper;
import com.chagee.store.operation.server.event.dao.TaskExecutionMapper;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.service.StoreConfigurationBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderReceiverBaseService;
import com.chagee.store.operation.server.model.param.WorkOrderExpiredTaskMqBody;
import com.chagee.store.operation.server.model.response.StoreTaskRelationResponse;
import com.chagee.store.operation.api.response.SupplierConfirmationResponse;
import com.chagee.store.operation.server.mq.WorkOrderExpiredTaskMqProduct;
import com.chagee.store.operation.server.service.base.StoreBaseService;
import com.chagee.store.operation.server.service.biz.SupplierDetailBizService;
import com.chagee.store.operation.server.utils.NumberUtil;
import com.chagee.storeManagement.api.event.enums.StoreCategoryEnum;
import com.chagee.storeManagement.api.event.enums.StoreWorkOrderStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName GenerateWorkOrderAndTaskExecutionTableData  //类名称
 * @Description: //类描述
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/7/10 10:17	//创建时间
 * @UpdateUser: Jacky-zhan  //变更者
 * @UpdateDate: 2024/7/10 10:17	//更新时间
 * @UpdateRemark: //更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Service
public class GenerateWorkOrderAndTaskExecutionTableData {


	@Resource
	private StoreTaskRelationMapper storeTaskRelationMapper;
	@Resource
	private WorkOrderMapper workOrderMapper;
	@Resource
	private TaskExecutionMapper taskExecutionMapper;
	@Resource
	private StoreMapper storeMapper;
	@Resource
	private RedisTemplate redisTemplate;
	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;
	@Resource
	private WorkOrderExpiredTaskMqProduct workOrderExpiredTaskMqProduct;
	//供应商确认的配置信息
	@Resource
	private SupplierConfirmationConfig supplierConfirmationConfig;

	@Resource
	private StoreConfigurationBaseService storeConfigurationBaseService;

	@Resource
	private SupplierDetailBizService supplierDetailBizService;

	@Resource
	private StoreBaseService storeBaseService;

	/**
	 * @Author: Lxy
	 * @Description: 生成打烊工单和打烊任务 数据
	 * @Date: 2024/3/1 10:17
	 * @Parms: [java.lang.String]
	 * @ReturnType: java.lang.Boolean
	 */
	@ExceptionLarkNotice(bizType = "生成打烊工单", title = "创建打烊工单和打烊任务", urgentType = UrgentTypeEnum.APP_PHONE)
	public Boolean generateData(String storeCode, String supplierName) {

		//更新工单表
		/**
		 * @Author: Lxy
		 * @see  StoreWorkOrderStatusEnum
		 */
		workOrderMapper.updateWhenDocumentStatusNoIn45(storeCode);
		//判断是否存在接单人信息，如果存在将数据状态置为已取消
		List<WorkOrderReceiverDO> workOrderReceiverDOList = workOrderReceiverBaseService.getAllByStoreCode(storeCode);
		if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
			workOrderReceiverDOList = workOrderReceiverDOList.stream()
				.peek(receiver -> receiver.setDocumentStatus(StoreWorkOrderStatusEnum.EXPIRED.getType()))
				.collect(Collectors.toList());
			workOrderReceiverBaseService.updateBatchById(workOrderReceiverDOList);
		}

		List<StoreTaskRelationResponse> storeTaskRelationResponseList = storeTaskRelationMapper.queryTaskRelationAndBasicTask(storeCode);
		if (CollectionUtils.isEmpty(storeTaskRelationResponseList)) {
			return true;
		}

		StoreConfigurationDO storeConfigurationDO = storeConfigurationBaseService.queryStoreConfig(storeCode);

		//生成工单表
		WorkOrderDO workOrderDO = new WorkOrderDO();
		HashMap<String, Object> map = new HashMap();
		map.put("store_no", storeCode);

		StoreDO storeDO = storeMapper.selectByMap(map).stream().findFirst().get();
		String storeName = storeDO.getStoreName();
		//加盟商
		String businessName = storeDO.getBusinessName();
		//门店性质
		String storeCategory = StoreCategoryEnum.queryByType(storeDO.getStoreCategory()).getType();
		String companyName = storeDO.getCompanyName();
		String workOrderNumber = NumberUtil.generateSerialNum(redisTemplate, "DY", 4);

		workOrderDO.setStoreName(storeName);
		workOrderDO.setStoreCode(storeCode);
		workOrderDO.setWorkOrderNumber(workOrderNumber);
		workOrderDO.setBusinessName(businessName);
		workOrderDO.setStoreCategory(storeCategory);
		workOrderDO.setCompanyName(companyName);
		//将门店的创建人和部门同步至工单表
		workOrderDO.setCreateUser(StringUtils.isNotBlank(storeDO.getCreateUser()) ? storeDO.getCreateUser() : "");
		workOrderDO.setCreateDept(StringUtils.isNotBlank(storeDO.getCreateDept()) ? storeDO.getCreateDept() : "");
		//需要将状态默认为待交接
		workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType());
		//供应商后面需要确认工单-设备的信息
		List<SupplierConfirmationResponse> describe = supplierConfirmationConfig.getDescribe();
		if (CollectionUtils.isNotEmpty(describe)) {
			//转成json对象存储
			workOrderDO.setDeviceTakeOver(JSON.toJSONString(describe));
		}
		workOrderDO.setSupplierNo(storeConfigurationDO.getSupplierNo());
		workOrderDO.setSupplier(supplierName);
		workOrderDO.setCompanyId(storeDO.getCompanyId());
		workOrderDO.setAppealFlag(OrderAppealTypeEnum.NO_APPEAL.name());
		workOrderMapper.insert(workOrderDO);

		//生成任务表
		for (StoreTaskRelationResponse storeTaskRelationResponse : storeTaskRelationResponseList) {
			TaskExecutionDO taskExecutionDO = new TaskExecutionDO();
			taskExecutionDO.setWorkOrderNumber(workOrderNumber);
			taskExecutionDO.setTaskId(storeTaskRelationResponse.getTaskId());
			taskExecutionDO.setTaskName(storeTaskRelationResponse.getTaskName());
			taskExecutionDO.setLiteralDescription(storeTaskRelationResponse.getWordDescribe());
			taskExecutionDO.setSchematicDrawing(storeTaskRelationResponse.getPictureStr());
			//新增字段赋值store_task_relation_id
			taskExecutionDO.setStoreTaskRelationId(storeTaskRelationResponse.getId());
			taskExecutionMapper.insert(taskExecutionDO);
		}
		//将工单添加到mq的延迟队列中
		WorkOrderExpiredTaskMqBody workOrderExpiredTaskMqBody = new WorkOrderExpiredTaskMqBody();
		workOrderExpiredTaskMqBody.setWorkOrderId(workOrderDO.getId());
		workOrderExpiredTaskMqBody.setWorkOrderNumber(workOrderDO.getWorkOrderNumber());
		Boolean b = workOrderExpiredTaskMqProduct.producerMessage(workOrderExpiredTaskMqBody);
		return true;
	}

	public Boolean createWorkOrder(String storeCode) {
		StoreDO storeDO = storeBaseService.queryStoreByStoreNo(storeCode);
		if (Objects.isNull(storeDO)) {
			throw new BizException(BizErrorCode.NOT_GTE_STORE_INFO);
		}
		if (!NumberUtils.INTEGER_ONE.equals(storeDO.getClosingTaskStatus())) {
			return false;
		}
		List<WorkOrderDO> workOrderDOS = workOrderMapper.selectListByCode(storeCode);
		if (CollectionUtils.isNotEmpty(workOrderDOS)) {
			throw new BizException(BizErrorCode.EXSIST_PROCESSING_WORK_ORDER);
		}
		List<SearchSupplierResponse> supplierList = supplierDetailBizService.supplierList();
		Map<String, String> supplierMap = supplierList.stream().filter(s -> org.apache.commons.lang3.StringUtils.isNotBlank(s.getCode())).collect(Collectors.toMap(SearchSupplierResponse::getCode, SearchSupplierResponse::getName, (a, b) -> b));

		StoreConfigurationDO storeConfigurationDO = storeConfigurationBaseService.queryStoreConfig(storeCode);

		String supplierName = org.apache.commons.lang3.StringUtils.EMPTY;
		if (MapUtil.isNotEmpty(supplierMap) && StringUtils.isNotBlank(supplierMap.get(storeConfigurationDO.getSupplierNo()))) {
			supplierName = supplierMap.get(storeConfigurationDO.getSupplierNo());
		}

		return this.generateData(storeCode, supplierName);
	}


}
